/**
 * Created by lwy on 2017/8/17.
 */

var typeValue = 2;
var ifIos = 0;
var ifandroid = 0;

var indexCategoryId = 1;
window.onload=function () {
    doBaseInfo();
    //doBanner();
    doFeature();
    doGoods();
}

function doBaseInfo() {
    $.ajax({
        url:'/indexConfigC/getConfig.json',
        dataType:'json',
        data:{
            companyCode:getItem('companyCode'),
        },
        success:function(data){
            //分类入口
            var cateData = data.datas.indexLabel;
            if(cateData.length>0){
                for(var b=0;b<cateData.length;b++){
                    $('<div class="swiper-slide" stateValue="'+cateData[b].id+'" url="'+cateData[b].url+'"><span>'+cateData[b].name+'</span></div>').appendTo($('#cateBox'))
                }
                //滑动导航
                var mySwiper = new Swiper('#topNav', {
                    freeMode: true,
                    freeModeMomentumRatio: 0.5,
                    slidesPerView: 'auto',

                });
                swiperWidth = mySwiper.container[0].clientWidth
                maxTranslate = mySwiper.maxTranslate();
                maxWidth = -maxTranslate + swiperWidth / 2
                mySwiper.on('tap', function(swiper, e) {

//	e.preventDefault()

                    slide = swiper.slides[swiper.clickedIndex]
                    slideLeft = slide.offsetLeft
                    slideWidth = slide.clientWidth
                    slideCenter = slideLeft + slideWidth / 2
                    // 被点击slide的中心点

                    mySwiper.setWrapperTransition(300)

                    if (slideCenter < swiperWidth / 2) {

                        mySwiper.setWrapperTranslate(0)

                    } else if (slideCenter > maxWidth) {

                        mySwiper.setWrapperTranslate(maxTranslate)

                    } else {

                        nowTlanslate = slideCenter - swiperWidth / 2

                        mySwiper.setWrapperTranslate(-nowTlanslate)

                    }

                    $("#topNav  .active").removeClass('active')

                    $("#topNav .swiper-slide").eq(swiper.clickedIndex).addClass('active');
                    var stateValue = $("#topNav .swiper-slide").eq(swiper.clickedIndex).attr('url');
                    window.location.href=stateValue;
                })
            }
            //轮播图入口
            var bannerData = data.datas.indexSlideshow;
            if(bannerData.length>0){
                for(var i=0;i<bannerData.length;i++){
                    $('<div class="swiper-slide">'+
                        '<a class="banner" href="'+bannerData[i].url+'">'+
                        '<img src="'+bannerData[i].img+'">'+
                        '</a></div>').appendTo($('#banner'));
                }
                var mySwiper = new Swiper ('.swiper-container4', {
                    loop: true,
                    autoplay: 5000,
                    pagination: '.swiper-pagination4',
                    paginationClickable: true,
                })
                mui('body').on('tap','.swiper-slide .banner',function(){
                    var href = $(this).attr('href');
                    window.location.href=href;
                })
            }
            //功能入口
            var funcData = data.datas.functionMenu;
            if(funcData.length>0){
                for(var c=0;c<funcData.length;c++){
                    $('<a href="'+funcData[c].url+'"><li><img src="'+funcData[c].img+'" alt=""><span>'+funcData[c].name+'</span></li></a>').appendTo($('.sort_box ul'))
                }
                if(funcData.length>0&&funcData.length<4){
                    var funWidth = 100/funcData.length;
                    $('#funcBox li').css({'width':funWidth+'%'});
                }
            }
        }
    })
}


mui('.sort_box ul').on('tap','a',function () {
    window.location.href=$(this).attr('href');
})



$(".swiper-container").on('touchstart', function(e) {
    e.preventDefault()
})



//首页轮播图
function doBanner(){
    $.ajax({
        url:'/bannerC/getBanner.json',
        dataType:'json',
        data:{
            typeValue:typeValue,
            companyCode:getItem('companyCode'),
        },
        success:function(data){
            for(var i=0;i<data.datas.length;i++){
                $('<div class="swiper-slide">'+
                    '<a class="banner" href="'+data.datas[i].url+'">'+
                    '<img src="'+data.datas[i].img+'">'+
                    '</a></div>').appendTo($('#banner'));
            }
            //轮播图
            var mySwiper = new Swiper ('.swiper-container4', {
                loop: true,
                autoplay: 5000,
                pagination: '.swiper-pagination4',
                paginationClickable: true,
            })
            //轮播图跳转
            mui('body').on('tap','.swiper-slide .banner',function(){
                var href = $(this).attr('href');
                window.location.href=href;
            })
        }
    })
}


//功能入口
function doFeature() {
    $.ajax({
        url:'/entranceC/getEntrance.json',
        dataType:'json',
        data:{
            indexCategoryId:indexCategoryId,
            companyCode:getItem('companyCode'),
        },
        type:'post',
        success:function (data) {
            var featureData = data.datas;
            $('#detail_box,#detail_box2').empty();
            if(featureData.entrance1.length>0){
                for(var i=0;i<featureData.entrance1.length;i++){
                    $('<div class="detail_box_container" url="'+featureData.entrance1[i].url+'">\n' +
                        '<span class="title">'+featureData.entrance1[i].name+'</span>\n' +
                        '<span class="small_title">'+featureData.entrance1[i].shortName+'</span>\n' +
                        '<img src="'+featureData.entrance1[i].img+'" alt="'+featureData.entrance1[i].name+'">\n' +
                        '</div>').appendTo($('#detail_box'));
                }
            }else{
                $('#detail_box').hide();
            }
            if(featureData.entrance2.length>0){
                for(var d=0;d<featureData.entrance2.length;d++){
                    if(featureData.entrance2[d].typeValue==3){
                        if(featureData.entrance2[d].seckillState){
                            $('<div class="detail_box_container" url="'+featureData.entrance2[d].url+'">\n' +
                                '<span class="title">'+featureData.entrance2[d].name+'</span>\n' +
                                '<span class="small_title">'+featureData.entrance2[d].shortName+'</span>\n' +
                                '<img src="'+featureData.entrance2[d].img+'" alt="'+featureData.entrance2[d].name+'">\n' +
                                '</div>').appendTo($('#detail_box2'));
                        }
                    }else {
                        $('<div class="detail_box_container" url="'+featureData.entrance2[d].url+'">\n' +
                            '<span class="title">'+featureData.entrance2[d].name+'</span>\n' +
                            '<span class="small_title">'+featureData.entrance2[d].shortName+'</span>\n' +
                            '<img src="'+featureData.entrance2[d].img+'" alt="'+featureData.entrance2[d].name+'">\n' +
                            '</div>').appendTo($('#detail_box2'));
                    }

                }
            }else{
                $('#detail_box2').hide();
            }
        }
    })
}

mui('body').on('tap','.detail_box_container',function () {
    window.location.href=$(this).attr('url');
})



var page = 0,
    num,
    unitPrice = 1;

//商品
function doGoods(){
    page++;
    $.ajax({
        url:'/openSearchC/goodSearch.json',
        dataType:'json',
        data:{
            page:page,
            isSales:1,
            companyCode:getItem('companyCode'),
        },
        type:'post',
        beforeSend:function(){
            if(page==1){
                $('<div class="loading" style="margin-top: 10px;"><img src="../phoneImg/jiazaizhong.gif"/></div>').appendTo($('#goods_box'));
            }
        },
        success:function(data){
            $('.loading').hide();
            var data2 = data.datas;
            if(page==1){
                $('#goods_box').empty();
                if(data2.length==0){
                    $('<div class="kong"><img src="../img/kong.png" alt="暂无数据"></div>').appendTo($('#goods_box'));
                }
            }
            for(var i=0;i<data2.length;i++){
                var goodsImg = data2[i].main_img.split(',');
                $('<div class="item2_box" goodsId="'+data2[i].goods_id+'">'+
                    '<div class="img"><img src="'+goodsImg[0]+'" alt=""></div>'+
                    '<div class="goods">'+
                    '<div class="title">'+data2[i].name+'</div>'+
                    '<div class="tips mui-clearfix"><span>正品保证</span><span>包邮</span><span>线上线下</span></div>'+
                    '<div class="stages mui-clearfix"><span><img src="../phoneImg/stages_icon.png" alt=""></span></div>'+
                    '<div class="price"><b>￥</b>'+data2[i].member_price+'</div>'+
                    '<div class="comment"><span>'+data2[i].commentNum+'人评价</span><span>'+data2[i].footMarkNum+'次浏览</span></div>'+
                    '</div></div>').appendTo($('#goods_box'))
            }
            num = data2.length;
        }
    })
    return num;
}

//
mui('body').on('tap','.item2_box',function () {
    var goodsId = $(this).attr('goodsId');
    window.location.href="goods.html?goodsId="+goodsId;
})

//mui下拉去掉一个滚动条
mui('.mui-scroll-wrapper').scroll({
    deceleration: 0.1, //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值 0.0006
    indicators: false   //隐藏一条滚动条 增大减速系数。。。
});

//上拉加载下拉刷新
mui.init({
    pullRefresh : {
        container:"#refreshContainer",//待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
        down: {
            contentdown : "下拉可以刷新",//可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
            contentover : "释放立即刷新",//可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
            contentrefresh : "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
            callback: function () {
                window.location.reload();
                mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
            }
        },
        up : {
            contentrefresh : "正在加载...",//可选，正在加载状态时，上拉加载控件上显示的标题内容
            contentnomore:'我是有底线的',//可选，请求完毕若没有更多数据时显示的提醒内容；
            callback :function(){
                setTimeout(function () {
                    var numResult = doGoods();
                    if (numResult < 20) {
                        mui('#refreshContainer').pullRefresh().endPullupToRefresh(true);
                    } else {
                        mui('#refreshContainer').pullRefresh().endPullupToRefresh(false);
                    }
                }, 1000);
            } //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
        }
    }
});

document.getElementById('mui-title').addEventListener('tap',function () {
    window.location.href="search.html";
})

document.getElementById('search-right').addEventListener('tap',function () {
    window.location.href=$(this).attr('href');
})

//是否登录
var token = getItem('token');
if(token==null||token==undefined||token==""){}else{
    ifHasNews();
}

if(GetQueryString('userId')==null||GetQueryString('userId')==undefined||GetQueryString('userId')==""){}else{
    setItem('userId',GetQueryString('userId'));
}

//是否有未读消息
function ifHasNews() {
    $.ajax({
        url:'/messagesC/countNotReadMessages.json',
        dataType:'json',
        type:'post',
        data:{token:token,companyCode:getItem('companyCode'),},
        success:function (data) {
            if(data.code==1){
                if(data.datas.count!=0){
                    $('#ifNews').show();
                }
            }
        }
    })
}